package T回溯;


import java.util.LinkedList;
import java.util.List;

/**
 * @author tmh
 * @date 2023/10/14 20:57
 * @description T216_组合综合III
 */
public class T216_组合综合III {
    List<List<Integer>> result = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        backTracking(k, n, 1);
        return result;
    }

    public void backTracking(int k, int n, int startIndex) {
        //深度剪枝
        if (path.stream().mapToInt(i -> i).sum() > n) {
            return;
        }

/*        if(path.size()==k&&path.stream().mapToInt(i->i).sum()==n){  if里面的判断条件会递归造成内存溢出
            result.add(new LinkedList<>(path));
            return;
        }*/

        if (path.size() == k) {
            if (path.stream().mapToInt(i -> i).sum() == n) {
                result.add(new LinkedList<>(path));
            }
            return;
        }
        for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
            path.add(i);
            backTracking(k, n, i + 1);
            path.removeLast();
        }
    }

    public static void main(String[] args) {
        T216_组合综合III t = new T216_组合综合III();
        List<List<Integer>> list = t.combinationSum3(3, 7);
        System.out.println(list);
    }
}
